module.exports = app => {
    const jwt = require('jsonwebtoken')
    const express = require("express")
    const assert = require('http-assert')

    const router  = express.Router({
        mergeParams:true //合并路由参数
    })
    /**
     * 新增分类到数据库中
     */
    router.post("/",async(req,res)=>{
        const model =  await req.Model.create(req.body)
        res.send(model)
    })
    /**
     * 根据ID更新分类
     */
    router.put("/:id",async(req,res)=>{
       const model =  await req.Model.findByIdAndUpdate(req.params.id,req.body)
       res.send(model)
    })
    /**
     * 请求10条分类数据
     */
    router.get("/",async(req,res)=>{
        const query ={}
        if(req.Model.modelName == "Category"){
            query.populate = "parent" //动态设置是否查询上级
        }
        const items =  await req.Model.find().setOptions(query).limit(100)
        res.send(items)
    })
    /**
     * 根据ID查找分类
     */
    router.get("/:id",async(req,res)=>{
        const cate =  await req.Model.findById(req.params.id)
        res.send(cate)
    })
    /**
     * 删除分类
     */
    router.delete("/:id",async(req,res)=>{
        const model =  await req.Model.findByIdAndDelete(req.params.id)
        res.send({
            success:true
        })
     })

    //用户验证中间件
    const authMiddleWare = require('../../middleware/auth')
    // 通用化中间件
    const resourceMiddleWare = require('../../middleware/resource')

    app.use("/admin/api/rest/:resource",authMiddleWare(),resourceMiddleWare(),router)



    const multer = require('multer')
    const MAO = require('multer-aliyun-oss')
    const upload = multer({
        // dest:__dirname+'/../../uploads'
        storage: MAO({
            config: {
                region: 'oss-cn-beijing',
                accessKeyId: 'LTAI4FwZzQjt6eyvGbYjKAFR',
                accessKeySecret: 'pEo9JZgc9pQTzxuALANmb7nM6mfLp1',
                bucket: 'moba0613'
            }
        })
    })

    app.post('/admin/api/upload',authMiddleWare(),upload.single('file'),(req,res)=>{
        const file = req.file
        // file.url = `http://39.106.198.9/uploads/${file.filename}`
        res.send(file)
    })

    app.post('/admin/api/login',async (req,res)=>{
        const {username,password} = req.body
        // 查找用户
        const AdminUser = require('../../models/AdminUser')
        const user = await AdminUser.findOne({username}).select('+password')
        assert(user,422,"用户不存在")
        // 检验密码
        const isValid = require('bcryptjs').compareSync(password,user.password)
        assert(isValid,422,"密码错误")
        // 返回Token
        
        const token = jwt.sign({id:user._id},app.get('secret'))
        return res.send({token,user:user.username})

    })

    //错误处理函数
    app.use(async (err,req,res,next)=>{
        res.status(err.statusCode || 500).send({
            message:err.message
        })
    })

}